package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.*;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/cargo/finance")
@Slf4j
public class FinanceController extends BaseController {

    // 注入dubbo的服务接口的代理对象
    @Reference
    private ContractService contractService;

    @Reference
    private ContractProductService contractProductService;

    @Reference
    private FinanceService financeService;

    @Reference
    private ExportService exportService;

    @Reference
    private PackingService packingService;

    @Reference
    private ExportProductService exportProductService;

    @Reference
    private InvoiceService invoiceService;

    @Reference
    private ShippingService shippingService;


    /**
     * 报运单列表
     */
    @RequestMapping("/list")
    public String list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize) {
        log.info("执行报运单列表分页的方法");

        PageInfo<Finance> pageInfo =
                financeService.findByPage(null, pageNum, pageSize);
        ;
        // 存储查询结果
        request.setAttribute("pageInfo", pageInfo);

        // 进入装箱管理列表
        return "cargo/finance/finance-list";
    }


    /**
     * 添加、修改
     */
    @RequestMapping("/edit")
    public String edit(Finance finance, Invoice invoice) {
        // 判断
        if (StringUtils.isEmpty(finance.getFinanceId())) {
            log.info("添加....");
            finance.setFinanceId(UUID.randomUUID().toString());
            finance.setInvoiceId(invoice.getInvoiceId());
            Invoice invoice1 = new Invoice();
            invoice1.setInvoiceId(invoice.getInvoiceId());
            invoice1.setStatus(1);
            invoiceService.updateByPrimaryKeySelective(invoice1);
            financeService.save(finance);
        } else {
            log.info("修改....");
            financeService.update(finance);
        }
        // 添加成功，重定向到报运单列表
        return "redirect:/cargo/finance/list";
    }

    /**
     * 装箱单列表，点击：查看
     * http://localhost:8080/cargo/contract/toView.do?id=6
     * http://localhost:8080/cargo/contract/submit.do?id=6
     * http://localhost:8080/cargo/contract/cancel.do?id=6
     */
    @RequestMapping("/toView")
    public String toView(String id) {
        log.info("执行购销合同查看.....");
        Finance finance = financeService.findById(id);
        request.setAttribute("finance", finance);
        return "cargo/finance/finance-view";
    }


    @RequestMapping("/toFinance")
    public String toFinance(String id) {
        Invoice invoice = invoiceService.selectByPrimaryKey(id);
        Shipping shipping = shippingService.findById(invoice.getShippingId());
        request.setAttribute("invoice", invoice);
        request.setAttribute("shipping", shipping);
        return "cargo/finance/finance-toFinance";
    }




    /**
     * 财务报运单表的POI导出 (2) 模板导出：先读取一个有样式的excel模板，再往里面填充数据
     */
    @RequestMapping("/financeExcel")
    public void financeExcel(String id) throws Exception {
        Finance finance = financeService.findById(id);
        Packing packing = packingService.findById(finance.getPackingListId());
        String[] split = packing.getExportIds().split(",");
        List<String> exportIdList = Arrays.asList(split);

        ExportExample exportExample = new ExportExample();
        exportExample.createCriteria().andIdIn(exportIdList);
        List<Export> exportList = exportService.findAll(exportExample);

        ExportProductExample exportProductExample = new ExportProductExample();
        exportProductExample.createCriteria().andExportIdIn(exportIdList);
        List<ExportProduct> exportProductList = exportProductService.findAll(exportProductExample);


        //【获取excel模板,文件流】
        InputStream in = request.getSession()
                .getServletContext()
                .getResourceAsStream("/make/xlsprint/finance.xlsx");

        // 第一：导出第一行
        Workbook workbook = new XSSFWorkbook(in);
        // 【获取工作表】
        Sheet sheet = workbook.getSheetAt(0);

        //【获取E2 设置制单日期】
        Row row = sheet.getRow(1);
        Cell cell = row.getCell(4);
        cell.setCellValue(new SimpleDateFormat("MMMM dd,yyyy", Locale.ENGLISH).format(finance.getInputDate()));


        //【获取P2 设置发票号】
        row = sheet.getRow(1);
        cell = row.getCell(16);
        cell.setCellValue(finance.getInvoiceId());

        //【设置合同号】
        row = sheet.getRow(2);
        cell = row.getCell(4);
        cell.setCellValue(finance.getExportNos());

        //【设置LCNO】
        row = sheet.getRow(2);
        cell = row.getCell(11);
        cell.setCellValue(exportList.get(0).getPriceCondition());
        row = sheet.getRow(4);
        cell = row.getCell(10);
        cell.setCellValue(exportList.get(0).getPriceCondition());
        row = sheet.getRow(3);
        cell = row.getCell(4);
        cell.setCellValue(exportList.get(0).getConsignee());
        row = sheet.getRow(3);
        cell = row.getCell(13);
        cell.setCellValue(exportList.get(0).getRemark());

        //【设置装运港】
        row = sheet.getRow(4);
        cell = row.getCell(2);
        cell.setCellValue(finance.getShipmentPort());

        //【设置目的港】
        row = sheet.getRow(4);
        cell = row.getCell(5);
        cell.setCellValue(finance.getDestinationPort());

        if (exportProductList != null && exportProductList.size() > 0) {
            int index = 7;
            for (ExportProduct exportProduct : exportProductList) {

                // 创建每一个数据行，从第7行开始
                row = sheet.getRow(index++);
                //货 号		厂 家	单位	数量	件数	"毛重
                //(kg)"	"净重
                //(kg)"	"尺 码
                //(cm)"			出口单价		单价	收 购 成 本
                //											单价	金额	单价	金额	税金
                cell = row.getCell(1);
                cell.setCellValue(exportProduct.getProductNo());
                row.getCell(4).setCellValue(exportProduct.getFactoryName());
                row.getCell(8).setCellValue(exportProduct.getGrossWeight());
                row.getCell(9).setCellValue(exportProduct.getFactoryName());
                row.getCell(10).setCellValue(exportProduct.getSizeHeight());
                row.getCell(11).setCellValue(exportProduct.getSizeWidth());
                row.getCell(12).setCellValue(exportProduct.getSizeLength());
                row.getCell(13).setCellValue(exportProduct.getPrice());
                row.getCell(14).setCellValue(exportProduct.getExPrice());
                row.getCell(15).setCellValue(exportProduct.getTax());
                row.getCell(16).setCellValue(exportProduct.getPrice());
                double d= exportProduct.getPrice()*0.17;
                row.getCell(17).setCellValue(d);

            }
        }


        // 第四：导出下载
        response.setCharacterEncoding("UTF-8");
        // 设置下载响应头（浏览器会以下载方式处理响应结果）
        response.setHeader("content-disposition", "attachment;filename=finance.xlsx");
        ServletOutputStream out = response.getOutputStream();
        // 把excel文件流，写入到response输出流，实现下载
        workbook.write(out);
        workbook.close();
        out.close();
    }


    //大标题的样式
    public CellStyle bigTitle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);                //横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);        //纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);                //横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);        //纵向居中
        style.setBorderTop(BorderStyle.THIN);                        //上细线
        style.setBorderBottom(BorderStyle.THIN);                    //下细线
        style.setBorderLeft(BorderStyle.THIN);                        //左细线
        style.setBorderRight(BorderStyle.THIN);                        //右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short) 10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);                //横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);        //纵向居中
        style.setBorderTop(BorderStyle.THIN);                        //上细线
        style.setBorderBottom(BorderStyle.THIN);                    //下细线
        style.setBorderLeft(BorderStyle.THIN);                        //左细线
        style.setBorderRight(BorderStyle.THIN);                        //右细线

        return style;
    }

}











